<template>
	<view class="box-container">
		<scroll-view class="main" scroll-y>
			<!-- 	<swiper class="header swiper" circular indicator-dots autoplay :interval="3000" :duration="1000">
				<swiper-item style="width: 100%; height: 100%; display: flex; justify-content: space-between">
					<image :src="product.image"></image>
				</swiper-item>
			</swiper> -->
			<view class="header swiper" style="width: 100%; display: flex; justify-content: center">
				<view style="width: 750rpx; height: 750rpx">
					<image style="width: 100%; height: 100%" :src="product.image"></image>
				</view>
			</view>

			<!-- 内容 -->
			<view class="main-child">
				<view class="product-info">
					<view class="name">{{ product.name }}</view>
					<view class="remark">{{ product.remark || '' }}</view>
				</view>

				<view v-if="product.type !== 2">
					<view class="materials" v-for="(material, index) in product.materials" :key="index">
						<view class="group-name" v-if="material.values.length > 0">{{ material.group_name }}</view>
						<view class="values" v-if="material.values.length > 0">
							<view
								class="value"
								:class="{ selected: value.is_selected, soldOut: value.isSoldOut }"
								@tap="changeMaterialSelected(index, key)"
								v-for="(value, key) in material.values"
								:key="key"
							>
								{{ value.fName }}
							</view>
						</view>
					</view>
				</view>
				<!-- 套菜 start -->
				<view class="set-meal" v-else>
					<view class="set-meal-item" v-for="(item, index) in materials" :key="index">
						<view class="materials-name">{{ item.group_name }}</view>
						<view class="product-item">
							<ProductItem
								:productObj="group"
								style="margin-top: 10rpx; margin-left: 10rpx"
								v-for="(group, i) in item.values"
								:key="group.id"
								@checkProduct="checkProduct(group, item, i, index)"
								@MealAdd="onMealAdd(group, item, i, index)"
								@MealMinus="onMealMinus(group, item, i, index)"
								@selectPractice="onSelectPractice(group, item, i, index, materials)"
							></ProductItem>
						</view>
					</view>
				</view>
				<!-- 套菜 end -->

				<view class="recommend-box" v-if="recommendList.length > 0">
					<view class="title">菜品推荐</view>
					<view class="recommend-content">
						<!-- <scroll-view scroll-x style="width: 100%; margin-top: 30rpx"> -->
						<view class="recommend-parent">
							<view
								class="product"
								:class="{ active: activeIndex === index || item.quantity }"
								v-for="(item, index) in recommendList"
								:key="item.id"
								@click="onCheckProduct(item, index)"
							>
								<image :src="item.image" mode=""></image>
								<view class="text" v-if="activeIndex !== index && !item.quantity" style="padding-left: 20rpx">
									<view style="font-size: 20rpx; color: #111111">{{ item.name.length > 9 ? item.name.slice(0, 6) + '...' : item.name }}</view>
									<view style="font-size: 22rpx; color: #111111">
										<text style="font-size: 18rpx">+</text>
										￥{{ item.realPrice }}
									</view>
								</view>
								<view class="action" v-else :style="{ marginLeft: item.quantity ? '20rpx' : '0' }">
									<view
										:style="{
											width: !item.quantity ? '40%' : '100%',
											marginLeft: !item.quantity ? '20rpx' : '0'
										}"
									>
										<Action
											@add="onAddCart(item)"
											@minus="onMinusCart"
											:number="item.quantity && item.type !== 2 ? item.quantity : 0"
											:materialsBtn="false"
										></Action>
									</view>
								</view>
							</view>
						</view>
						<!-- </scroll-view> -->
					</view>
				</view>

				<view class="product-image" v-if="product.introduce">
					<view class="title">商品详情</view>
					<view class="content" v-html="product.introduce"></view>
				</view>
			</view>
		</scroll-view>

		<view class="footer">
			<view class="modify-num">
				<!-- 普通菜价格start -->
				<view style="color: #b9b9b9; font-size: 22rpx" v-if="product.type === 1">
					<text style="font-size: 40rpx; color: #e1684c; margin-right: 10rpx">
						<!-- ￥{{ product.type === 1 ? getPrice : userInfo.id ? (product.vipPrice ? product.vipPrice : product.price) : product.price }} -->
						￥{{ getPrice }}
					</text>
					<text v-if="product.vipPrice" :class="{ del: userInfo.id }" style="font-size: 25rpx">
						<!-- 原价 ￥{{ product.type === 1 ? getOriginalCost : product.price }} -->
						原价 ￥{{ getOriginalCost }}
					</text>
				</view>
				<!-- 普通菜价格end -->
				<!-- 套菜价格start -->
				<view style="color: #b9b9b9; font-size: 22rpx" v-else>
					<text style="font-size: 40rpx; color: #e1684c; margin-right: 10rpx">￥{{ comboPrice }}</text>
					<text v-if="product.vipPrice" :class="{ del: userInfo.id }" style="font-size: 25rpx">原价 ￥{{ comboCostPrice }}</text>
				</view>
				<!-- 套菜价格 end -->

				<Action :number="product.number" :materialsBtn="false" @minus="onMinus" @add="product.number++"></Action>
			</view>
			<!-- 显示规格套菜 -->
			<view v-if="product.type === 2" @click="queryDetail" style="color: #b9b9b9; font-size: 22rpx; margin-top: 10rpx">
				{{ getSpecification.length > 26 ? getSpecification.slice(0, 26) + '... 查看明细 >' : getSpecification }}
			</view>
			<!--  普通菜 -->
			<view v-else style="color: #b9b9b9; font-size: 22rpx; margin-top: 10rpx">
				{{ getSpecification.length > 70 ? getSpecification.slice(0, 70) + '...' : getSpecification }}
			</view>
			<view class="btn-box">
				<view>
					<!-- 如果是套菜时套菜已售罄也要禁用按钮 -->
					<u-button :disabled="isDisabled || materialsOtherData.isSoldOut" color="#9e8465" shape="circle" plain @click="addCart(true, true)">立即购买</u-button>
				</view>
				<view>
					<u-button :disabled="isDisabled || materialsOtherData.isSoldOut" shape="circle" type="primary" @click="addCart(false, false)">加入购物车</u-button>
				</view>
			</view>
		</view>

		<view style="position: fixed; left: 20rpx" :style="{ top: menuButton.top + 'px' }" @click="onBack" v-if="systemInfo.hostName === 'WeChat'">
			<image :style="{ width: menuButton.height + 'px', height: menuButton.height + 'px' }" src="../../static/images/index/round-cancel.png" mode=""></image>
		</view>
		<u-toast ref="uToast"></u-toast>

		<!-- 套菜中的菜是否有规格 -->
		<productPopup
			:bottom="30"
			:materialsOtherData="materialsOtherData"
			:visible="productVisible"
			@cancel="onCancel('normal')"
			:product="sentProduct"
			@add-to-cart="addProduct"
		></productPopup>

		<!-- 选中套菜详细 -->
		<DetailPopup ref="openDetailPopup" :temporaryList="temporaryList"></DetailPopup>

		<!-- 推荐菜选择规格 -->
		<productPopup
			:bottom="30"
			:materialsOtherData="recommendOtherData"
			:visible="recommendVisible"
			@cancel="onCancel('recommend')"
			:product="recommendProduct"
			@add-to-cart="addRecommendProduct"
		></productPopup>

		<!-- 购物车弹框 -->
		<cart-popup :cart="cart" ref="cartPopupRef" @add="addShopCart" @minus="minusShopCart" @clear="clearCart"></cart-popup>
	</view>
</template>

<script>
import Action from '@/pages/tab_bar/classify/components/actions/actions.vue';
import ProductItem from '@/components/product-item/index.vue';
import productPopup from '@/pages/tab_bar/classify/components/product-popup/product-popup.vue';
import cartPopup from '@/pages/tab_bar/classify/components/cart-popup/cart-popup.vue';
import DetailPopup from './components/DeatilPopup.vue';
import { mapState, mapMutations } from 'vuex';
import common from '@/common/util.js';
export default {
	components: {
		Action,
		ProductItem,
		productPopup,
		DetailPopup,
		cartPopup
	},
	data() {
		return {
			isDisabled: false,
			activeIndex: -1, // 选中的推荐菜
			product: {},
			materials: [],
			productInfo: {},
			recommendList: [],
			deskId: 0,
			orderId: 0,
			productId: 0,
			isDetail: false, // 判断是否从菜品推荐的详情页跳转
			productVisible: false,
			sentProduct: {}, // 套菜的规格要使用productPopup必须处理数据
			temporaryList: [], // 临时数据（套菜选中同一数据）
			materialsOtherData: {},
			systemInfo: common.getSystemInfo(),
			recommendOtherData: {}, // 推荐菜规格数据
			recommendProduct: {}, // 推荐菜规格数据
			recommendVisible: false, // 展示推荐菜规格
			cartPopupShow: false, // 展示购物车全部数据
			shopCartList: [],
			cart: []
		};
	},
	onShow() {
		this.MenuButton_Client();
		this.deskId = uni.getStorageSync('deskId') || 0;
		this.orderId = uni.getStorageSync('orderId') || 0;
	},
	onLoad({ productId, isDetail }) {
		if (productId) {
			this.productId = productId;
			this.getProductDetail(true);
		}
		if (isDetail) {
			this.isDetail = isDetail;
		}
	},
	computed: {
		...mapState(['stock', 'userInfo', 'menuButton']),
		getPrice() {
			const data = this.product;
			// console.log(data);
			if (this.userInfo.id) {
				// 有会员价
				if (data.materials) {
					const selectedItems = []; // 用于存储选中的项
					for (const group of data.materials) {
						for (const value of group.values) {
							if (value.is_selected) {
								if (value.vipPrice !== 0) {
									// 有优惠
									selectedItems.push(value.vipPrice);
								} else {
									selectedItems.push(value.fPosPrice);
								}
							}
						}
					}
					// 将选中项的价格与外部 price 相加
					// const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, externalPrice);

					const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, 0);
					return (price * data.number).toFixed(2);
				} else {
					// 有会员没规格start
					if (data.vipPrice) {
						return (data.vipPrice * data.number).toFixed(2);
					} else {
						return (data.price * data.number).toFixed(2);
					}
					// 有会员没规格end
				}
			} else {
				// 没优惠
				if (data.materials) {
					const selectedItems = []; // 用于存储选中的项
					// const externalPrice = data.FPosPrice; // 外部的 price
					for (const group of data.materials) {
						for (const value of group.values) {
							if (value.is_selected) {
								selectedItems.push(value.fPosPrice);
							}
						}
					}
					// 将选中项的价格与外部 price 相加
					// const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, externalPrice);
					const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, 0);
					return (price * data.number).toFixed(2);
				} else {
					// if(data.vipPrice) {
					// 	return (data.vipPrice * data.number).toFixed(2)
					// } else {
					return (data.price * data.number).toFixed(2);
					// }
				}
			}
		},
		getSpecification() {
			// 选中规格文字
			const arr = [];
			if (this.product.type === 2) {
				// 套菜
				// 将每个菜选中后插入materials，，没选就给个默认
				this.temporaryList.forEach((item, index) => {
					item.values.forEach((v) => {
						if (v.selectQuantity) {
							arr.push(v.foodName + '：');
							if (v.materials) {
								for (const group of v.materials) {
									for (const value of group.values) {
										if (value.is_selected) {
											arr.push(value.fName + '￥ ');
											if (value.vipPrice !== 0 && this.userInfo.id) {
												arr.push(value.vipPrice + ' ');
											} else {
												arr.push(value.fPosPrice + ' ');
											}
										}
									}
								}
							} else {
								// 没有规格
								arr.push('默认做法； ');
							}
						}
					});
				});
			} else {
				//  普通菜
				if (this.product.materials) {
					for (const group of this.product.materials) {
						for (const value of group.values) {
							if (value.is_selected) {
								arr.push(value.fName + '￥ ');
								if (value.vipPrice !== 0 && this.userInfo.id) {
									arr.push(value.vipPrice + ' ');
								} else {
									arr.push(value.fPosPrice + ' ');
								}
							}
						}
					}
				}
			}

			return arr.join('');
		},
		// 原价
		getOriginalCost() {
			const data = this.product;
			if (data.materials) {
				const selectedItems = []; // 用于存储选中的项
				// const externalPrice = data.FPosPrice; // 外部的 price
				for (const group of data.materials) {
					for (const value of group.values) {
						if (value.is_selected) {
							selectedItems.push(value.fPosPrice);
						}
					}
				}
				// 将选中项的价格与外部 price 相加
				// const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, externalPrice);
				const price = selectedItems.reduce((total, itemPrice) => total + itemPrice, 0);
				return (price * data.number).toFixed(2);
			} else {
				// if(data.vipPrice) {
				// 	return (data.vipPrice * data.number).toFixed(2)
				// } else {
				return (data.price * data.number).toFixed(2);
				// }
			}
		},
		// 套菜价格
		comboPrice() {
			const data = this.product;
			if (this.userInfo.id) {
				let priceList = [];
				// 有会员价
				this.temporaryList.forEach((group, a) => {
					group.values.forEach((value, b) => {
						if (value.selectQuantity && value.price) {
							priceList.push(value.quantity * value.price);
						}
					});
				});
				// console.log(
				//   555555555555,
				//   priceList.reduce((a, b) => a + b, 0)
				// );
				if (data.vipPrice) {
					return (data.number * (data.vipPrice + priceList.reduce((a, b) => a + b, 0))).toFixed(2);
				} else {
					return (data.number * (data.price + priceList.reduce((a, b) => a + b, 0))).toFixed(2);
				}
			} else {
				// 没有会员价
				let priceList = [];
				this.temporaryList.forEach((group, a) => {
					group.values.forEach((value, b) => {
						if (value.selectQuantity && value.price) {
							priceList.push(value.quantity * value.price);
						}
					});
				});
				return (data.number * (data.price + priceList.reduce((a, b) => a + b, 0))).toFixed(2);
			}
		},
		// 套菜原价
		comboCostPrice() {
			const product = this.product;
			let priceList = [];
			this.temporaryList.forEach((group, a) => {
				group.values.forEach((value, b) => {
					if (value.selectQuantity && value.price) {
						priceList.push(value.quantity * value.price);
					}
				});
			});
			return product.number * (product.price + priceList.reduce((a, b) => a + b, 0)).toFixed(2);
		}
	},
	methods: {
		...mapMutations(['MenuButton_Client']),
		async getProductDetail(isShopCart) {
			if (isShopCart) {
				await this.getShopCartList();
			}
			const res = await this.$api.GetSpecBySubId({
				FSubItemID: this.productId || this.product.id,
				storeId: this.stock.id
			});
			this.materialsOtherData = JSON.parse(JSON.stringify(res.otherData));
			this.materials = JSON.parse(JSON.stringify(res.data));
			this.temporaryList = JSON.parse(JSON.stringify(res.data));
			this.product = res.otherData;
			this.$set(this.product, 'materials', res.data);
			this.$set(this.product, 'number', 1);
			this.recommendList = JSON.parse(JSON.stringify(res.otherData.recommendList));
			this.recommendList.forEach((ele) => {
				this.$set(ele, 'quantity', 0);
			});
			// this.product.materials = res.data

			this.recommendListNumber();

			/*
			 isDisabled:表示固定选好不用自己选
			 checkQuantity： 表示当前菜的选的数量
				totalQuantity：表示固定当前规格总数，当选了当个菜的某个以后总数超过则不可选
				*/
			// 2表示套菜
			if (this.product.type === 2) {
				this.materials.forEach((v, index) => {
					// 判断是否有加料
					v.values.forEach((item) => {
						if (item.otherData.length > 0) {
							this.$set(item, 'isCharge', true);
						} else {
							this.$set(item, 'isCharge', false);
						}
					});

					if (v.selectType === 2) {
						// 固定菜不可选
						v.values.forEach((i, index2) => {
							this.$set(i, 'selectQuantity', 1);
							this.$set(i, 'isDisabled', true);
							this.$set(this.temporaryList[index].values[index2], 'selectQuantity', 1);
						});
					} else {
						// 其他菜可选
						this.$set(v, 'totalQuantity', 0);
						v.values.forEach((i) => {
							this.$set(i, 'selectQuantity', 0);
							this.$set(i, 'isDisabled', false);
						});
					}
				});
			}
		},
		// 获取购物车列表
		async getShopCartList() {
			// 获取购物车列表
			const res = await this.$api.GetShoppingCart({
				storeId: this.stock.id,
				deskId: this.deskId,
				orderId: this.orderId
			});
			this.shopCartList = res.data.foodList;
			this.updateCart(this.shopCartList);
		},
		// 点击添加菜
		async onAddCart(item) {
			// 1.如果当前菜是普通菜直接添加即可，如果是套菜跳转详细页
			// 2. 获取购物车数据，比对推荐菜是否有数据展示number
			// 3. 页面展示按钮
			if (item.type === 2) {
				// 套菜跳转
				this.$u.route('/pages/product/product_detail', { productId: item.id, isDetail: true });
				return;
			}
			// 调用规格 获取数据
			const res = await this.$api.GetSpecBySubId({
				FSubItemID: item.id,
				storeId: this.stock.id
			});
			this.recommendOtherData = res.otherData; // 推荐菜规格数据
			this.recommendProduct = JSON.parse(JSON.stringify(item)); // 推荐菜规格数据
			this.recommendProduct.materials = res.data;
			this.recommendVisible = true; // 展示推荐菜规格
		},
		onMinusCart(item) {
			// 减少购物车数据
			this.$refs.cartPopupRef.open();
		},
		onMinus() {
			if (this.product.number > 1) {
				this.product.number = this.product.number - 1;
			}
		},

		changeMaterialSelected(index, key) {
			const currentRow = this.product.materials[index];
			if (currentRow.group_name === '规格') {
				if (currentRow.values.length > 1) {
					if (currentRow.values[key].isSoldOut) {
						return;
					}
					currentRow.values.forEach((value) => {
						this.$set(value, 'is_selected', false);
					});
					currentRow.values[key].is_selected = true;
				}
			} else if (currentRow.group_name === '加料') {
				currentRow.values[key].is_selected = !currentRow.values[key].is_selected;
			} else {
				if (!currentRow.values[key].selectType) {
					currentRow.values[key].is_selected = !currentRow.values[key].is_selected;
				} else {
					currentRow.values.forEach((value) => {
						if (value.selectType) {
							value.is_selected = false;
						}
					});
					currentRow.values[key].is_selected = true;
				}
			}
			// const currentMaterial = this.product.materials[index].values[key]; //materials每一项规格中的其中一个规格
			// // 判断单选还是多选
			// if (currentMaterial.selectType === 1) return; // 如果selectType=1不可以选择
			// if (!currentMaterial.is_exclusive) {
			// 	if (currentMaterial.is_selected) return;
			// 	this.product.materials[index].values.forEach((value) => this.$set(value, 'is_selected', 0));
			// 	currentMaterial.is_selected = 1;
			// 	if (index === 0) {
			// 		this.product.FFoodSpecID = currentMaterial.fItemID;
			// 	}
			// } else {
			// 	currentMaterial.is_selected = !currentMaterial.is_selected;
			// }
		},
		addCart(isTemp, isBuy) {
			let _that = this;
			console.log(56565, isTemp, isBuy, _that);
			// 判断是否套菜
			if (_that.product.type === 2) {
				_that.materials.forEach((item, index) => {
					if (item.selectType !== 2) {
						item.values.forEach((v) => {
							if (!v.selectQuantity && !item.isSelectSame && item.selectType === 1 && item.totalQuantity < item.quantityEnd) {
								// 没有选择 且 不能选同一个菜 且 =1是可选 且 选择总数量 没选够数量
								//  不能选择相同菜，需要每一项都勾选一份
								_that.showToast('可选菜未选够数量', 'error');
								throw new Error('可选菜未选够数量');
							} else {
								if (item.quantityEnd !== item.totalQuantity) {
									if ((item.selectType === 1 && item.isSelectSame) || item.selectType === 3) {
										_that.showToast('菜未选够数量', 'error');
										throw new Error('菜未选够数量');
									}
								}
							}
						});
					}
				});
			}

			_that.isDisabled = true;
			// 普通菜
			if (_that.product.materials && _that.product.type === 1) {
				_that.product.feed_ids = _that.product.materials[1].values.filter((im) => im.is_selected).map((jm) => jm.fItemID);
				_that.product.tast_ids = _that.product.materials[2].values.filter((im) => im.is_selected).map((jm) => jm.fItemID);

				// this.productData .feed_ids = this.productData.materials[1].values.filter((im) => im.is_selected).map((jm) => jm.fItemID);
				// _that.product.specId = _that.product.materials[0].values.find((item) => item.is_selected).fItemID;
				const fItem = _that.product.materials[0].values.find((item) => item.is_selected);
				if (!fItem) {
					uni.showToast({
						title: '当前未选中规格'
					});
					return;
				}
				// this.productData.specId = fItem.fItemID;
				this.product.specId = fItem.fItemID;
			}
			// 套菜
			const detailList = [];
			if (_that.product.type === 2) {
				// _that.materials.forEach((i) => {
				_that.temporaryList.forEach((i) => {
					i.values.forEach((item) => {
						if (item.selectQuantity) {
							detailList.push({
								foodSpecId: item.foodSpecId,
								foodId: item.foodId,
								quantity: item.quantity,
								// selectQuantity: item.selectQuantity * item.quantity,
								id: item.id,
								setPrice: item.setPrice,
								feed_ids: item.feed_ids || [],
								tast_ids: item.tast_ids || []
							});
						}
					});
				});
			}

			const product = {
				..._that.product
			};
			_that.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: product.number || 1, // 数量
					feed_ids: product.feed_ids || [], // 做法
					tast_ids: product.tast_ids || [], //
					FFoodSpecID: product.FFoodSpecID || product.specId, // 规格
					deskId: _that.deskId,
					orderId: _that.orderId,
					isTemp: isTemp ? true : false,
					isBuy: isBuy ? true : false,
					detailList: detailList || [],
					foodType: product.type === 2 ? 2 : 1
				})
				.then(async (res) => {
					if (isTemp) {
						// 立即购买
						if (_that.deskId) {
							// 立即购买直接下单，桌台
							await uni.showModal({
								title: '下单提示',
								content: '是否立即下单',
								async success(res) {
									if (res.confirm) {
										await _that.$api.placeOrder({
											orderId: _that.orderId,
											deskId: _that.deskId,
											remark: _that.remark,
											isTemp,
											isBuy
										});
										// 快餐
										// uni.navigateTo({
										//   url: '/pages/pay/pay_order/index?isTemp=' + true + '&isBuy=' + true
										// });
										// uni.showModal({
										// 	title:'温馨提示',
										// 	content:'是否立即下单',
										// 	success(){

										// 	}
										// })
										uni.navigateTo({
											url: '/pages/order/confirm_success'
										});
									}
								},
								complete() {
									_that.isDisabled = false;
								}
							});
							return;
						}
						// 加入购物车
						uni.navigateTo({
							url: '/pages/order/pay?isTemp=' + true + '&isBuy=' + true
						});
						_that.isDisabled = false;
						return;
					}
					if (_that.isDetail) {
						// 菜品跳转的直接返回
						uni.navigateBack();
						_that.isDisabled = false;
						return;
					}
					uni.switchTab({
						url: '/pages/tab_bar/classify/classify'
					});
					_that.isDisabled = false;
				})
				.finally(() => {
					_that.isDisabled = false;
				});
		},
		onBack() {
			uni.navigateBack();
		},
		onCheckProduct(item, index) {
			// 选中当前菜品
			if (index === this.activeIndex) {
				this.activeIndex = -1;
				return;
			}
			this.activeIndex = index;
		},
		// item 规格中每一项 row 每一项规格
		checkProduct(item, row, index, i) {
			if (row.selectType === 2) return this.showToast('固定菜已搭配好了', 'error');
			if (row.quantityEnd <= row.totalQuantity) return this.showToast('该分组已经选好了', 'error'); // && !item.selectQuantity
			if (!row.isSelectSame && item.selectQuantity) return;
			if (item.otherData.length < 1) {
				if (item.selectQuantity) return;
				// 没有做法
				if (!row.isSelectSame) {
					// 不能选择同一项
					item.selectQuantity = 1;
					row.totalQuantity = row.totalQuantity + 1;
					item.isDisabled = true;
					this.temporaryList[i].values[index].selectQuantity = 1;
					this.onToatl(row, item);
				} else {
					// 不能选择同一项
					item.selectQuantity = 1;
					row.totalQuantity = row.totalQuantity + 1;
					this.temporaryList[i].values[index].selectQuantity = 1;
					this.onToatl(row, item);
				}
				return;
			}
			this.productVisible = true;
			this.setSentProduct(item, row, index, i);
		},
		// 选择做法
		addProduct(e) {
			// 如果同一数据添加过将他放在零时数据里面
			this.materials.forEach((v, index) => {
				// if (v.selectType === e.type) {
				if (index === e.rowIndex) {
					if (v.values[e.index].selectQuantity) {
						if (e.type !== 2) {
							this.temporaryList[index].values.push({
								...v.values[e.index],
								feed_ids: e.feed_ids,
								tast_ids: e.tast_ids,
								materials: e.materials,
								price: +e.price
							});
						} else {
							this.temporaryList[e.rowIndex].values[e.index].materials = e.materials;
							v.values[e.index].feed_ids = e.feed_ids;
							v.values[e.index].tast_ids = e.tast_ids;
							this.temporaryList[e.rowIndex].values[e.index].feed_ids = e.feed_ids;
							this.temporaryList[e.rowIndex].values[e.index].tast_ids = e.tast_ids;
							this.temporaryList[e.rowIndex].values[e.index].price = e.price;
							// 改变this.temporaryList 触发computed
							this.temporaryList.push([]);
							this.temporaryList.pop();
						}
					} else {
						v.values[e.index].feed_ids = e.feed_ids;
						v.values[e.index].tast_ids = e.tast_ids;
						this.temporaryList[index].values[e.index].feed_ids = e.feed_ids;
						this.temporaryList[index].values[e.index].tast_ids = e.tast_ids;
						this.temporaryList[index].values[e.index].selectQuantity = 1;
						this.temporaryList[index].values[e.index].materials = e.materials;
						this.temporaryList[index].values[e.index].price = e.price;
						// 改变this.temporaryList 触发computed
						this.temporaryList.push([]);
						this.temporaryList.pop();
					}

					if (e.type !== 2 && v.totalQuantity < v.quantityEnd) {
						v.values[e.index].selectQuantity = v.values[e.index].selectQuantity + 1;
						v.totalQuantity = v.totalQuantity + 1;
					}
					this.onToatl(v);
				}
				// 判断可选菜是否选完数量
				if ((v.selectType === 1 && v.totalQuantity >= v.quantityEnd) || (v.selectType === 3 && v.totalQuantity >= v.quantityEnd)) {
					v.values.forEach((i) => {
						i.isCharge = false;
					});
				}
				// 判断是否是可选同一种菜
				if (v.selectType === 1 && v.totalQuantity < v.quantityEnd) {
					v.values.forEach((i) => {
						if (v.isSelectSame) {
							i.isCharge = true;
							i.isDisabled = false;
						} else {
							if (i.selectQuantity) {
								i.isCharge = false;
								i.isDisabled = true;
							} else {
								i.isCharge = true;
								i.isDisabled = false;
							}
						}
					});
				}
			});
			this.productVisible = false;
			this.sentProduct = {};
		},
		// 添加按钮
		onMealAdd(item, row, index, i) {
			// if (item.selectQuantity) {
			//   // 如果已经选择过加料就不用展示弹框
			//   item.selectQuantity = item.selectQuantity + 1;
			//   row.totalQuantity = row.totalQuantity + 1;
			//   this.onToatl(row);
			//   return;
			// }
			if (item.otherData.length < 1) {
				item.selectQuantity = item.selectQuantity + 1;
				row.totalQuantity = row.totalQuantity + 1;
				// this.temporaryList[i].values[index].selectQuantity = this.temporaryList[i].values[index].selectQuantity + 1;
				this.temporaryList[i].values.push(this.temporaryList[i].values[index]);
				this.onToatl(row);
				return;
			}
			this.productVisible = true;
			this.setSentProduct(item, row, index, i);
			this.onToatl(row);
		},
		// 减少按钮
		onMealMinus(item, row, index, i) {
			if (row.selectType === 2) return this.showToast('固定菜不可修改');
			// 如果同一菜品数据弹出弹出层在进行删除
			if (row.isSelectSame && row.selectType === 1) {
				let array = this.temporaryList[i].values;
				const count = array.filter((row) => row.id === item.id).length;
				if (count > 1) {
					// 找到最后一个相同 ID 的索引
					const lastIndex =
						array.length -
						1 -
						array
							.slice()
							.reverse()
							.findIndex((row) => row.id === item.id);
					const removedItem = array.splice(lastIndex, 1); // 删除最后一个相同 ID 的元素
				} else {
					this.temporaryList[i].values[index].selectQuantity = this.temporaryList[i].values[index].selectQuantity - 1;
					// 改变this.temporaryList 触发computed
					this.temporaryList.push([]);
					this.temporaryList.pop();
				}

				// this.temporaryList[i].values.forEach((v.index)=> {

				// 	this.temporaryList[i].values.splice(index,1)
				// })
				item.selectQuantity = item.selectQuantity - 1;
				row.totalQuantity = row.totalQuantity - 1;
			} else {
				item.selectQuantity = item.selectQuantity - 1;
				row.totalQuantity = row.totalQuantity - 1;
				this.temporaryList[i].values[index].selectQuantity = this.temporaryList[i].values[index].selectQuantity - 1;
			}

			if (row.totalQuantity < row.quantityEnd && row.selectType === 1) {
				row.values.forEach((v) => {
					if (row.isSelectSame) {
						// 可选 并且能选相同菜 isCharge 是否显示选规格
						v.isCharge = true;
						v.isDisabled = false;
					} else {
						if (v.selectQuantity) {
							v.isCharge = false;
							v.isDisabled = true;
						} else {
							v.isCharge = true;
							v.isDisabled = false;
						}
					}
				});
			} else if (row.totalQuantity < row.quantityEnd && row.selectType === 3) {
				// 几个选一个
				row.values.forEach((v) => {
					v.isCharge = true;
					v.isDisabled = false;
				});
			}
		},
		queryDetail() {
			if (this.product.type === 1) return;
			// 查看详情
			this.$refs.openDetailPopup.open();
		},

		// 判断总数是否已经满了，是禁用其他选项
		onToatl(row, item) {
			// values，每一项
			if (row.selectType === 2) return;
			if (row.quantityEnd <= row.totalQuantity) {
				row.values.forEach((v) => {
					v.isDisabled = true;
					v.isCharge = false;
				});
			} else {
				row.values.forEach((v) => {
					if (!row.isSelectSame && v.isDisabled) {
						v.isDisabled = true;
					} else {
						v.isDisabled = false;
					}
				});
			}
		},
		// 选择做法
		onSelectPractice(item, row, index, rowIndex, xxxx) {
			this.productVisible = true;
			this.setSentProduct(item, row, index, rowIndex);
		},
		setSentProduct(item, row, index, rowIndex) {
			this.sentProduct = {
				activityPrice: 0,
				description: item.description || '',
				id: item.id,
				image: item.image,
				materials: item.otherData,
				name: item.foodName,
				number: 1,
				price: 0,
				shopQty: 0,
				sort: 0,
				spec: item.specName,
				specId: item.foodSpecId,
				type: row.selectType,
				vipPrice: 0,
				isSetMenu: true,
				index,
				rowIndex
			};
		},
		// 关闭弹出层
		onCancel(type) {
			if (type === 'recommend') {
				this.recommendVisible = false;
				this.recommendProduct = {};
				this.recommendOtherData = {};
			} else {
				this.productVisible = false;
				this.sentProduct = {};
			}
		},
		// 添加数据
		showToast(message, type) {
			this.$refs.uToast.show({
				message,
				type
			});
		},
		addRecommendProduct(product) {
			// 推荐菜添加到购物车
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: product.number || 1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId,
					foodType: product.foodType,
					FShoppingCartID: product.foodType === 2 ? product.FShoppingCartID : 0
				})
				.then((res) => {
					this.shopCartList = res.data.foodList;
					this.updateCart(this.shopCartList);
					this.recommendListNumber();
					this.onCancel('recommend');
				});
		},
		recommendListNumber() {
			// 处理推荐菜数量问题
			this.recommendList.forEach((item) => {
				item.quantity = 0;
				if (item.type == 2) {
					item.quantity = 0;
				} else {
					this.shopCartList.forEach((e) => {
						if (item.id === e.fFoodID) {
							item.quantity += e.fQty;
						}
					});
				}
			});
		},
		updateCart(shopcart) {
			// 传递get购物车数据
			this.cart = shopcart.map((im) => {
				return {
					description: im.description,
					vipPrice: im.vipPrice, // 会员价格
					FItemID: im.fSubItemID,
					FFoodID: im.fFoodID,
					FName: im.fName,
					FPosPrice: im.fPosPrice,
					number: im.fQty,
					FPic: im.fProImage,
					FSpec: im.fSpec,
					FFoodSpecID: im.fFoodSpecID,
					FRemark: im.fRemark,
					FeedTasteNames: im.feedTasteNames,
					FShoppingCartID: im.fShoppingCartID || 0,
					feed_ids: im.feedData.length > 0 ? im.feedData.map((jm) => jm.fFeedID) : [],
					tast_ids: im.tastData.length > 0 ? im.tastData.map((jm) => jm.fTastID) : [],
					detailList: im.detailList ? im.detailList || [] : [],
					foodType: im.foodType || 0
				};
			});
		},
		addShopCart(product) {
			// 全部购物车数据添加
			console.log(product);
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: 1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId,
					foodType: product.foodType,
					FShoppingCartID: product.foodType === 2 ? product.FShoppingCartID : 0
				})
				.then((res) => {
					this.shopCartList = res.data.foodList;
					this.updateCart(res.data.foodList);
					this.recommendListNumber();
				});
		},
		minusShopCart(product) {
			// 全部购物车数据减少
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: -1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId,
					foodType: product.foodType,
					FShoppingCartID: product.foodType === 2 ? product.FShoppingCartID : 0
				})
				.then((res) => {
					this.shopCartList = res.data.foodList;
					this.updateCart(res.data.foodList);
					this.recommendListNumber();
				});
		},
		clearCart() {
			// 全部购物车数据清空
			this.$api
				.DelCart({
					deskId: this.deskId
				})
				.then((res) => {
					this.updateCart([]);
					this.shopCartList = [];
					this.recommendListNumber();
				});
		}
	}
};
</script>

<style scoped lang="scss">
@import '@/pages/product/product_detail.scss';
</style>
